import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

import 'package:my_flutter/Model/post.dart';

class HttpDemo extends StatelessWidget {
  const HttpDemo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HttpDemo'),
        elevation: 0.0,
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  HttpDemoHome({Key key}) : super(key: key);

  @override
  _HttpDemoHomeState createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {
  @override
  void initState() {
    super.initState();

    // fetchPosts();

    final postData = {'title': 'hello', 'description': 'nice to meet you'};
    print('title: ${postData['title']}');
    print('description: ${postData['description']}');
    final postJson = jsonEncode(postData);
    print(postJson);

    final postJsonConverted = jsonDecode(postJson);
    print(postJsonConverted['title']);
    print(postJsonConverted['description']);
    print(postJsonConverted is Map);

    final postModel = Post.fromJson(postJsonConverted);
    print('${postModel.title}');
  }

  fetchPosts() async {
    final response =
        await http.get('https://resources.ninghao.net/demo/posts.json');

    if (response.statusCode == 200) {
      final responseDecode = jsonDecode(response.body);
      return responseDecode['posts']
          .map<Post>((item) => Post.fromJson(item))
          .toList();
    } else {
      throw Exception('data is error');
    }
  }

  Widget build(BuildContext context) {
    return FutureBuilder(
        future: fetchPosts(),
        builder: (BuildContext context, AsyncSnapshot snapData) {
          if (snapData.connectionState == ConnectionState.waiting) {
            return Center(
              child: Text('loading...'),
            );
          }
          return ListView(
            children: snapData.data.map<Widget>((item) {
              return ListTile(
                title: Text(item.title),
                subtitle: Text(item.author),
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(item.imageUrl),
                ),
              );
            }).toList(),
          );
        });
  }
}

class Post {
  final int id;
  final String title;
  final String author;
  final String description;
  final String imageUrl;

  Post({this.id, this.title, this.author, this.description, this.imageUrl});

  Post.fromJson(Map json)
      : id = json['id'],
        title = json['title'],
        author = json['author'],
        description = json['description'],
        imageUrl = json['imageUrl'];
}
